/*
 * Copyright 2009 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ui.app.com.utile;

import android.util.Log;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Iterator;
import java.util.Vector;

/**
 * 用来找到系统中可以用的串口的，如果你知道的android设备有什么串口，
 * 就不必使用这个类来查找串口了
 */
public class SerialPortFinder {
    private static SerialPortFinder serialPortFinder;
    private final String TAG = "SerialPort";
    private Vector<Driver> drivers = null;

    public static SerialPortFinder getInstance() {
        if (serialPortFinder == null) {
            serialPortFinder = new SerialPortFinder();
        }
        return serialPortFinder;
    }


    public String[] getAllDevices() {
        Vector<String> devices = new Vector();
        // Parse each driver
        Iterator<Driver> itdriv;
        try {
            itdriv = getDrivers().iterator();
            while (itdriv.hasNext()) {
                Driver driver = itdriv.next();
                Iterator<File> itdev = driver.getDevices().iterator();
                while (itdev.hasNext()) {
                    String device = itdev.next().getName();
                    String value = String.format("%s (%s)", device, driver.getName());
                    devices.add(value);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return devices.toArray(new String[devices.size()]);
    }

    public String[] getAllDevicesPath() {
        Vector<String> devices = new Vector<String>();
        // Parse each driver
        Iterator<Driver> itdriv;
        try {
            itdriv = getDrivers().iterator();
            while (itdriv.hasNext()) {
                Driver driver = itdriv.next();
                Iterator<File> itdev = driver.getDevices().iterator();
                while (itdev.hasNext()) {
                    String device = itdev.next().getAbsolutePath();
                    devices.add(device);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return devices.toArray(new String[devices.size()]);
    }

    //获取串口
    private Vector<Driver> getDrivers() throws IOException {
        if (drivers == null) {
            drivers = new Vector();
            LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
            String l;
            while ((l = r.readLine()) != null) {
                // Issue 3:
                // Since driver name may contain spaces, we do not extract driver name with split()
                String drivername = l.substring(0, 0x15).trim();
                Log.e(TAG, "getDrivers找到串口1：" + drivername + " drivername:" + l);

                String[] w = l.split(" +");
                if ((w.length >= 5) && (w[w.length - 1].equals("serial"))) {
                    Log.e(TAG, "getDrivers找到串口：" + drivername + " 路径：" + w[w.length - 4]);
                    drivers.add(new Driver(drivername, w[w.length - 4]));
                }
            }
            r.close();
        }
        return drivers;
    }

    public class Driver {
        private String driverName;
        private String deviceRoot;
        Vector<File> devices = null;

        public Driver(String name, String root) {
            driverName = name;
            deviceRoot = root;
        }

        public Vector<File> getDevices() {
            if (devices == null) {
                initDevices();
            }
            return devices;
        }

        //
        private void initDevices() {
            devices = new Vector();
            File dev = new File("/dev");
            Log.e("dev", " 是否存在：" + dev.exists() +
                    " 路径:" + dev.getAbsolutePath() + " 匹配参数:" + deviceRoot + " " + driverName);
            File[] files = dev.listFiles();
            File tyy = new File("/dev/tty");
            File ttyS2 = new File("/dev/ttyS2");
            Log.e("dev", " tty文件：" + (tyy.exists()));
            Log.e("dev", " ttyS2文件：" + (ttyS2.exists()));
            Log.e("dev", " 子文件：" + (files == null));
            if (files == null) {
                return;
            }
            Log.e("dev", " 子文件数：" + (files.length));
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                String path = f.getAbsolutePath();
                Log.e("dev", " 子文件：" + path + " 匹配参数：" + deviceRoot);
                if (path.startsWith(deviceRoot)) {
                    Log.e(TAG, "dev找到串口: " + path);
                    devices.add(f);
                }
            }
        }

        public String getName() {
            return driverName;
        }
    }
}
